package com.rrd.hive.udf;

import com.weicai.caesar.CaesarUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.security.NoSuchAlgorithmException;


@Description(
        name = "caesar_sha256",
        value = "_FUNC_(str) - sha256 encode str or caesar encode str",
        extended = "Example:\n> SELECT _FUNC_('13811360000');\n  867DA37CD2C283605767208A95D0DAF5E872947D2EA263348F1589159EBCA51A\n> SELECT _FUNC_('6jxdXEKdEo/bHVdtUWshLZmfEBahoIMjHUUtRRjvrJM=');\n  867DA37CD2C283605767208A95D0DAF5E872947D2EA263348F1589159EBCA51A"
)
public class CaesarSha256UDF extends UDF {

    public Text evaluate(String str) throws NoSuchAlgorithmException {
        Text text = new Text();
        if (str == null || str.equals("")) {
            return null;
        }
        String s;
        if (CaesarUtil.isEncrypted(str)) {
            s = getSha256(CaesarUtil.decode(str));
        } else {
            s = getSha256(str);
        }
        text.set(s);

        return text;
    }

    /**
     * SHA256加密
     *
     * @param str
     * @return
     */
    public static String getSha256(String str) {
        return DigestUtils.sha256Hex(str).toUpperCase();
    }

    public static void main(String[] args) throws Exception {
        CaesarSha256UDF udf = new CaesarSha256UDF();
        System.out.println(udf.evaluate("13811360000").toString());

    }
}
